package com.afdor.rws.event.driven.channel.consumer.handler;


import com.afdor.rws.event.driven.entities.Event;
import lombok.NonNull;

/**
 * 事件处理器代理对象
 *
 * @author 悭梵
 * @date Created in 2018-12-05 16:09
 */
public class ProxyEventHandler implements EventHandler {
    /**
     * 原始事件处理器对象
     */
    private final EventHandler targetEventHandler;

    public ProxyEventHandler(@NonNull EventHandler eventHandler) {
        this.targetEventHandler = eventHandler;
    }

    @Override
    public Object handler(Event event) {
        try {
            event.setStatus(Event.Status.EXECUTING);
            return this.targetEventHandler.handler(event);
        } catch (Exception e) {
            if (event.getRetryCount() <= 6) {
                event.setStatus(Event.Status.FAILURED);
            } else {
                event.setStatus(Event.Status.TERMINATED);
            }
            if (e instanceof RuntimeException) {
                throw (RuntimeException) e;
            }
            throw new RuntimeException(e);
        }
    }
}
